package example.hellosecurity.example.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

import java.io.IOException;

/**
 * @ClassName ForwardAuthenticationSuccessHandler 的自定义
 * @Describtion:
 * @Author:Chenc
 * @Date:2024/1/17 11:59
 * @Version 1.0
 */
public class MyForwardAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private final String forwardUrl;

    public MyForwardAuthenticationSuccessHandler(String forwardUrl) {
//        Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl), () -> {
//            return "'" + forwardUrl + "' is not a valid forward URL";
//        });
        this.forwardUrl = forwardUrl;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        User credentials = (User) authentication.getCredentials();

        response.sendRedirect(this.forwardUrl);
    }
}
